package model

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	. "liteblog/src/common"
	_ "liteblog/src/common"
	"log"
	"os"
	"time"
)

var orm *xorm.Engine

func init() {
	SetEngine()
}
func SetEngine() *xorm.Engine {
	log.Println("db initializing...")
	var err error
	server := Cfg.MustValue("db", "server", "127.0.0.1")
	username := Cfg.MustValue("db", "username", "root")
	password := Cfg.MustValue("db", "password", "root")
	dbName := Cfg.MustValue("db", "db_name", "blog")
	orm, err = xorm.NewEngine("mysql", username+":"+password+"@tcp("+server+":3306)/"+dbName+"?charset=utf8")
	if err != nil {
		log.Panicln(err)
	}
	orm.SetTableMapper(core.SameMapper{})
	orm.SetColumnMapper(core.SameMapper{})
	orm.TZLocation = time.Local
	orm.ShowSQL = Cfg.MustBool("db", "show_sql", true)
	orm.Logger = xorm.NewSimpleLogger(os.Stdout)
	return orm
}

type DbUtil struct{}

/*
func (self *DbUtil) GetRecentComments() (comments []Comment) {
    err := orm.OrderBy("create_date desc").Limit(5, 0).Find(&comments, &Comment{})
    PanicIf(err)
    return
}

func (self *DbUtil) GetHotBlog() (blog []Blog) {
    result, err := orm.Query("select * from  blog b, (select  blog_id, count(*) count from comment group by blog_id  order by count desc limit 0,5) t where b.id = t.blog_id order by t.count desc, b.create_date desc")
    PanicIf(err)
    for _, val := range result {
        b := Blog{Id: int(ParseInt(string(val["id"]))), Title: string(val["title"])}
        blog = append(blog, b)
    }
    return
}

func (self *DbUtil) GetAllLinks() (links []Link) {
    err := orm.OrderBy("create_date desc").Find(&links, &Link{})
    PanicIf(err)
    return links
}*/
